package sip

import (
	"fmt"
	"log"
	"strconv"

	"gitee.com/larry_wan/go-lib/siprocket"
)

type Context struct {
	Server    *Server
	Transport *Transport
	Req       *Request
	SipMsg    *siprocket.SipMsg

	abort bool
}

func (c *Context) Abort() {
	c.abort = true
}

type HandleFunc func(c *Context)

func (c *Context) GetReqSerial() (serial string) {
	var err error
	defer func() {
		if p := recover(); p != nil {
			err = fmt.Errorf("get sip req serial error, %v", p)
		}
		if err != nil {
			log.Println(err)
		}
	}()
	serial = string(c.SipMsg.Req.User)
	return
}

func (c *Context) GetReqRealm() (realm string) {
	var err error
	defer func() {
		if p := recover(); p != nil {
			err = fmt.Errorf("get sip req realm error, %v", p)
		}
		if err != nil {
			log.Println(err)
		}
	}()
	host := string(c.SipMsg.Req.Host)
	port := string(c.SipMsg.Req.Port)
	if port != "" {
		realm = fmt.Sprintf("%s:%s", host, port)
	} else {
		realm = host
	}
	return
}

func (c *Context) GetFromSerial() (serial string) {
	var err error
	defer func() {
		if p := recover(); p != nil {
			err = fmt.Errorf("get sip from serial error, %v", p)
		}
		if err != nil {
			log.Println(err)
		}
	}()
	serial = string(c.SipMsg.From.User)
	return
}

func (c *Context) GetFromRealm() (realm string) {
	var err error
	defer func() {
		if p := recover(); p != nil {
			err = fmt.Errorf("get sip from realm error, %v", p)
		}
		if err != nil {
			log.Println(err)
		}
	}()
	host := string(c.SipMsg.From.Host)
	port := string(c.SipMsg.From.Port)
	if port != "" {
		realm = fmt.Sprintf("%s:%s", host, port)
	} else {
		realm = host
	}
	return
}

func (c *Context) GetViaPort() (port uint) {
	var err error
	defer func() {
		if p := recover(); p != nil {
			err = fmt.Errorf("get sip port error, %v", p)
		}
		if err != nil {
			log.Println(err)
		}
	}()
	strPort := string(c.SipMsg.Via[0].Port)
	nPort, err := strconv.Atoi(strPort)
	if err != nil {
		return
	}
	port = uint(nPort)
	return
}
